﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using CMN.Common;
using CMN.Controllers.View;
using CMN.Config;
using System.Web.Security;
using CMN.Extends.Job;
using System.Text;
using System.Text.RegularExpressions;
namespace CMN.MvcWeb
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            CMN.Controllers.Mvc.Routing.RouteTableRegister.RegisterRoutes(routes);
           
           

            RouteTable.Routes.RouteExistingFiles = true;  //可以直接浏览已经存在的文件，不会经过路由。
           
        }

        protected void Application_Start()
        {
          
            AppLog.Init();
            AppLog.Write("Web开启...", AppLog.LogMessageType.Info);

            MvcHandler.DisableMvcResponseHeader = true;
            MvcViewEngine mvcView = new MvcViewEngine();
            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(mvcView);

            //AreaRegistration.RegisterAllAreas();
            RegisterRoutes(RouteTable.Routes);
            //计划任务
            Jobs.Instance.LoadJobs();
            
        }

        protected void Application_BeginRequest(){
            
            string strUrl =HttpContext.Current.Request.Url.LocalPath.ToLower();
            if (strUrl.EndsWith(".htm"))
            {
                if (!Utils.IsExistsFile(Utils.GetMapPath(strUrl)))
                {
                    Response.Clear();
                    Response.StatusCode = 301;
                    Response.Status = "301 Moved Permanently";
                    Response.AddHeader("Location", strUrl.Replace(".htm", ""));
                    Response.End();
                }
            }
            else if (strUrl.EndsWith(".gif") || strUrl.EndsWith(".jpg") || strUrl.EndsWith(".png") || strUrl.EndsWith(".css") || strUrl.EndsWith(".js") || strUrl.EndsWith(".ico") || strUrl.EndsWith(".jpeg"))
            {

            }
            else
            {
                Regex reg = new Regex(@"^[-a-zA-Z0-9]{0,62}\.[-a-zA-Z0-9]{0,62}$");
               // [a-zA-Z0-9][-a-zA-Z0-9]{0,62}(/.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+/.?
               //string  str=HttpContext.Current.Request.Url.Host;
                //AppLog.Write("host:" + HttpContext.Current.Request.Url.Host, AppLog.LogMessageType.Info);
               if (reg.IsMatch(HttpContext.Current.Request.Url.Host))
               {
                   //AppLog.Write("host:" + HttpContext.Current.Request.Url.Host, AppLog.LogMessageType.Info);
                   //AppLog.Write("Authority:" + HttpContext.Current.Request.Url.Authority, AppLog.LogMessageType.Info);
                   //AppLog.Write("LocalPath:" + HttpContext.Current.Request.Url.LocalPath, AppLog.LogMessageType.Info);
                  
                   Response.Clear();
                   Response.StatusCode = 301;
                   Response.Status = "301 Moved Permanently";
                   if (HttpContext.Current.Request.Url.LocalPath == "/")
                   {
                       Response.AddHeader("Location", string.Concat(HttpContext.Current.Request.Url.Scheme,"://",  "www.", HttpContext.Current.Request.Url.Host));
                   }
                   else
                   {
                       Response.AddHeader("Location", string.Concat(HttpContext.Current.Request.Url.Scheme, "://",  "www.", HttpContext.Current.Request.Url.Host, HttpContext.Current.Request.Url.LocalPath));
                   }
                  
                   Response.End();
               }
            }
            
             
        }
        void Application_End(object sender, EventArgs e)
        {
            //在应用程序关闭时运行的代码

            AppLog.Write("Web站点关闭...", AppLog.LogMessageType.Info);

        }
        void Application_Error(object sender, EventArgs e)
        {
            //在出现未处理的错误时运行的代码
            Exception ex = Server.GetLastError();
            if (ex != null)
            {
                //写入错误日志
              

                //如果是 HttpException 异常 不处理, 显示403 404 页面
                if (ex is HttpException)
                {
                    HttpException httpEx = ex as HttpException;
                    if (httpEx.GetHttpCode() == 403 || httpEx.GetHttpCode() == 404)
                        return;
                }
                if (Request != null)
                    AppLog.Write(string.Concat("客户机IP:", Request.UserHostAddress, "     错误地址:", Request.Url, "   异常信息:"), AppLog.LogMessageType.Error, ex);
                else
                    AppLog.Write("   异常信息:", AppLog.LogMessageType.Error, ex);
            }

        }

        void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
            
            ////判断是否在manager目录里,并且文件名为aspx
            //if ( Utils.GetScriptUrl.ToLower().Contains("/manager/"))
            //{
            //    AppLog.Write("app_AuthMethod" + DateTime.Now.Second + "**" + DateTime.Now.Millisecond, AppLog.LogMessageType.Info);
            //    //检测方法权限设置
            //    HttpApplication App = (HttpApplication)sender;
            //    string cookieName = FormsAuthentication.FormsCookieName;
            //    HttpCookie authCookie = App.Context.Request.Cookies[cookieName];

            //    if (null == authCookie)
            //    {
            //        // 沒有驗證 Cookie。
            //        return;
            //    }

            //    FormsAuthenticationTicket authTicket = null;
            //    try
            //    {
            //        authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            //    }
            //    catch (Exception ex)
            //    {
            //        // 記錄例外狀況詳細資料 (為簡單起見已省略)

            //        return;
            //    }

            //    if (null == authTicket)
            //    {
            //        // Cookie 無法解密。
            //        return;
            //    }

            //    // 建立 Identity 物件
            //    FormsIdentity id = new FormsIdentity(authTicket);
            //    App.Context.User = new PermissionPrincipal(id);
                
            //}
        }
    }
}